import os

class Notebook:
    def __init__(self, notebookPath):
        self.path = notebookPath
        self.title = self.path[:-3]
        self.f = None

        self.rewriteTitle()
        
        self.catalogue = list()

        self.readNotebook()
        self.getHead()

    def readNotebook(self):
        with open(self.path, 'r', encoding='utf-8') as f:
            self.f = f.readlines()
    def getHead(self):
        for l in self.f:
            if '# ' in l:
                self.catalogue.append(self.rewriteCatalogue(l))

    def rewriteCatalogue(self, catalogue: str):
        if catalogue[1] != ' ':
            cl = catalogue.split()
            return '\- '*(len(cl[0])-2)*2 + '  ' + cl[-1] + '\n\n'
        else:
            return '# ' + self.title + '\n\n'

    def rewriteTitle(self):
        with open(self.path, 'r', encoding='utf-8') as f:
            f_l = f.readlines()
        f_l[0] = f"# {self.title} \n\n"
        with open(self.path, 'w+', encoding='utf-8') as f:
            f.writelines(f_l)

    def print(self):
        print(f"笔记标题：{self.title}")
        for h in self.catalogue:
            print(h)

class README:
    def __init__(self):
        self.notebookpaths = self.getNotes()
        self.notelist = list()
        self.catalogues = list()

        self.head = '''
# 华北电力大学《发电厂电气部分》课程笔记


习题来自张奶奶的课后作业题与答案。

作者水平有限，如有错误可以在 Issues 反馈。



求张奶奶给我过了吧！！！


------
# 目录



        '''


        for notebookpath in self.notebookpaths:
            self.notelist.append(Notebook(notebookpath))

        self.readCatalogue()

    def getNotes(self):
        files = os.listdir()
        notebooks = list()
        for f in files:
            if '.md' in f and f != 'README.md' and f != 'catalogue.md':
                print(f'读取到笔记：{f}')
                notebooks.append(f)
        return notebooks

    def readCatalogue(self):
        for n in self.notelist:
            self.catalogues += n.catalogue

    def write(self):
        with open('README.md', 'w+', encoding='utf-8') as f:
            f.writelines([self.head, '\r\n']+self.catalogues)

if __name__ == '__main__':
    rd = README()
    rd.write()


